package cevent.source.cloudcenter.server.service;

import cevent.source.cloudcenter.server.domain.*;
import cevent.source.cloudcenter.server.dto.PageDto;
import cevent.source.cloudcenter.server.dto.RolesDto;
import cevent.source.cloudcenter.server.mapper.RolesEmployeeMapper;
import cevent.source.cloudcenter.server.mapper.RolesMapper;
import cevent.source.cloudcenter.server.mapper.RolesResourcesMapper;
import cevent.source.cloudcenter.server.util.DuplicateUtil;
import cevent.source.cloudcenter.server.util.UUID8Util;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author cevent
 * @description 角色管理表服务层
 */
@Service
public class RolesService {
    private static final Logger LOG=LoggerFactory.getLogger(RolesService.class);
    @Resource
    private RolesMapper rolesMapper;
    //保存角色资源关联数据
    @Resource
    private RolesResourcesMapper rolesResourcesMapper;
    //保存角色-员工关联数据
    @Resource
    private RolesEmployeeMapper rolesEmployeeMapper;

    //1.无分页列表查询：dto获取domain参数
    public List<RolesDto> rolesDtoList(){
        RolesExample rolesExample = new RolesExample();
        rolesExample.setOrderByClause("uni_id asc");
        List<Roles> rolesList=rolesMapper.selectByExample(rolesExample);
        List<RolesDto> rolesDtoList = new ArrayList<RolesDto>();
        for(int i=0;i<rolesList.size();i++){
            Roles roles=rolesList.get(i);
            RolesDto rolesDto=new RolesDto();
            //复制拷贝(source,target)
            BeanUtils.copyProperties(roles,rolesDto);
            rolesDtoList.add(rolesDto);
        }
        return rolesDtoList;
    }

    /*2.分页查询：pageDto保存数据
        list数据集合：listPageData
        当前页码：currentPage
        每页行数：size
        总计函数：totalSize
        前端可返回pageDto，无需返回值
     */
    public void getRolesPageDtoList(PageDto pageDto){
        //1.分页设置（前端传入当前页和每页行数params），起始页，每页行数size
        PageHelper.startPage(pageDto.getCurrentPage(),pageDto.getSize());

        RolesExample rolesExample=new RolesExample();


        List<Roles> rolesList=rolesMapper.selectByExample(rolesExample);
        //2.将mapper查询结果复制到pageInfo
        PageInfo<Roles> pageInfo=new PageInfo<>(rolesList);
        //3.pageInfo计算处理处理=>后分页的总行数set到pageDto做记录
        pageDto.setTotalSize(pageInfo.getTotal());

        List<RolesDto> rolesDtoList=new ArrayList<>();
        rolesList.stream().forEach(roles->{
            RolesDto rolesDto=new RolesDto();
            BeanUtils.copyProperties(roles,rolesDto);
            rolesDtoList.add(rolesDto);
        });

        pageDto.setListPageData(rolesDtoList);

    }

    //3.新增、修改roles，将传入的id转为roles对象本身
    public void save(RolesDto rolesDto){
        Roles roles= DuplicateUtil.copy(rolesDto,Roles.class);
        if(StringUtils.isEmpty(rolesDto.getUniId())){
            this.insert(roles);
        }else{
            this.update(roles);
        }

    }

    //4.删除模块：多表开启事务
    @Transactional
    public void delete(String uniId){
        RolesExample rolesExample=new RolesExample();
        rolesMapper.deleteByPrimaryKey(uniId);
        RolesResourcesExample rolesResourcesExample=new RolesResourcesExample();
        //创建条件查询，根据rolesId获取角色资源
        rolesResourcesExample.createCriteria().andRolesIdEqualTo(uniId);
        //删除角色资源数据
        rolesResourcesMapper.deleteByExample(rolesResourcesExample);
    }

    //5.向外暴露dto，不暴露实体类：插入数据
    private void insert(Roles roles){
        roles.setUniId(UUID8Util.getShortUUID());

        try {
        Date now =new Date();
        String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
        long time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
        int timeInt=(int)(time/1000);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        rolesMapper.insert(roles);
    }

    //6.更新模块
    private void update(Roles roles){
        try {
            Date now =new Date();
            String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);
            long time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();
            int timeInt=(int)(time/1000);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        rolesMapper.updateByPrimaryKey(roles);
    }

    //7.保存角色资源:多表开启事务
    @Transactional
    public RolesDto saveRolesResources(RolesDto rolesDto){
        String rolesId=rolesDto.getUniId();
        //保存角色信息
        Roles roles=new Roles();
        if(StringUtils.isEmpty(rolesId)){
            roles.setUniId(UUID8Util.getShortUUID());
            roles.setName(rolesDto.getName());
            roles.setPrivilegeDesc(rolesDto.getPrivilegeDesc());
            rolesMapper.insert(roles);
        }else{
            roles.setUniId(rolesId);
            roles.setName(rolesDto.getName());
            roles.setPrivilegeDesc(rolesDto.getPrivilegeDesc());
            rolesMapper.updateByPrimaryKey(roles);
        }
        List<String> resourcesId=rolesDto.getResourcesId();
        //7.1清空rolesId下所有rolesResources数据
        RolesResourcesExample rolesResourcesExample=new RolesResourcesExample();
        //创建条件，获取所有rolesId相关数据
        rolesResourcesExample.createCriteria().andRolesIdEqualTo(rolesId);
        //根据条件，删除
        rolesResourcesMapper.deleteByExample(rolesResourcesExample);
        //遍历，保存角色资源
        for(int i=0;i<resourcesId.size();i++){
            RolesResources rolesResources=new RolesResources();
            rolesResources.setUniId(UUID8Util.getShortUUID());
            rolesResources.setRolesId(rolesId);
            rolesResources.setResourcesId(resourcesId.get(i));
            rolesResourcesMapper.insert(rolesResources);
        }

        return rolesDto;
    }
    //保存角色-员工关联
    @Transactional
    public RolesDto saveRolesEmployeeByIds(RolesDto rolesDto){
        String rolesId=rolesDto.getUniId();
        List<String> employeeId=rolesDto.getEmployeeId();
        //1.清空rolesId下的rolesEmployee数据
        RolesEmployeeExample rolesEmployeeExample=new RolesEmployeeExample();
        rolesEmployeeExample.createCriteria().andRolesIdEqualTo(rolesId);
        rolesEmployeeMapper.deleteByExample(rolesEmployeeExample);
        //遍历保存角色-员工
        for(int i=0;i<employeeId.size();i++){
            RolesEmployee rolesEmployee=new RolesEmployee();
            rolesEmployee.setUniId(UUID8Util.getShortUUID());
            rolesEmployee.setRolesId(rolesId);
            rolesEmployee.setEmployeeId(employeeId.get(i));
            rolesEmployeeMapper.insert(rolesEmployee);
        }
        return rolesDto;
    }
}
